<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/22
 * Time: 9:58
 * 签到
 */
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\FundsRecord;
use app\common\model\SignCount;
use think\Db;
use think\Exception;

class Sign extends Api {
	
	protected $noNeedRight = '*';
	
	
	/**
	 * 签到状态及积分查询
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function signStatus(){
		$userId = $this->auth->id;
		$row = Db::name('signCount')
			->where(['user_id' => $userId])
			->find();
		//昨天的0点时间
		$checkTime = strtotime(date('Y-m-d', strtotime('-1 days')));
		if(!$row || $row['update_time'] < $checkTime) {
			$days = 0;
		} else {
			$days = $row['days'];
		}
		
		//签到状态
		$signStatus = 0;
		if($row && $row['update_time'] > strtotime(date('Y-m-d'))) {
			$signStatus = 1;
		}
		
		$returnData = [
			'days' => $days,
			'point' => $this->auth->voucher_balance,
			'sign_status' => $signStatus
		];
		
		$this->success('查询成功', $returnData);
	}
	
	/**
	 * 签到
	 */
	public function sign(){
		$userId = $this->auth->id;
		$row = Db::name('signCount')
			->where(['user_id' => $userId])
			->find();
		//昨天的0点时间
		$checkTime = strtotime(date('Y-m-d', strtotime('-1 days')));
		
//		签到状态
		if($row && $row['update_time'] > strtotime(date('Y-m-d'))) {
			$this->error('今天已经签到了');
		}
		
		$setting = Db::name('signSetting')
			->order(['day' => 'DESC'])
			->column('point', 'day');
		
		$model = new SignCount();
		Db::startTrans();
		try {
			//添加签到记录
			if(!$row) {
				//没有签到过
				$signRes = $model->isUpdate(false)
					->save([
						'user_id' => $userId,
						'days' => 1]);
				$days = 1;
			} else {
				//昨天天没签到，今天算第一天
				if($row['update_time'] < $checkTime) {
					$days = 1;
				} else {
					$days = $row['days']+1;
				}
				$signRes = $model
					->save([
						'user_id' => $userId,
						'days' => $days
					],['id' => $row['id']]);
			}
			
			if(!$signRes) {
				throw new Exception('添加签到记录出错');
			}
			
			//如果有配置送积分，给用户送积分和添加资金记录
			if($setting) {
				//设置的最大天数，总签到记录大于这个，奖励重新计算
				$maxDay = max(array_keys($setting));
				$countDay = $days;
				
				$signDays = $days;
				if($signDays > $maxDay) {
					$signDays = $days%$maxDay;
				}
				
				if(isset($setting[$signDays]) && $setting[$signDays] > 0) {
					$amount = $setting[$signDays];
					
					$userRes = Db::name('user')->where(['id' => $userId])
						->setInc('voucher_balance', $amount);
					if(!$userRes) {
						throw new Exception('添加用户优惠券出错');
					}
					
					$logModel = new FundsRecord();
					$logRes = $logModel->addRecord($userId, $amount, $this->auth->voucher_balance, $logModel::ACCOUNT_TYPE_VOUCHER, $logModel::OPE_TYPE_PLUS, $logModel::TYPE_SIGN,'', '签到第'.$countDay.'天');
					if(!$logRes) {
						throw new Exception('添加资金记录出错');
					}
				}
			}
			
			Db::commit();
			$user = Db::name('user')->find($userId);
			$this->success('签到成功', ['point' => $user['voucher_balance'], 'days' => $days]);
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		
	}
}